﻿using EntityCreater.Entity;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityCreater.Service
{
    public class CoreService
    {
        /// <summary>
        /// 根据连接字符串获取该数据库中的所有表
        /// </summary>
        /// <param name="connStr"></param>
        /// <returns></returns>
        public static List<TableInfo> GetTableInfoByConnStr(string connStr)
        {
            return new SQLBuilder.Repositories.SqlRepository(connStr).FindList<TableInfo>(@"
select [name] AS TableName,[id] AS TableId from sysobjects where [type] = 'u' order by [name]
").ToList();
        }

        public static List<FieldInfo> GetFieldListByTableName(string tableName, string connStr)
        {
            return new SQLBuilder.Repositories.SqlRepository(connStr).FindList<FieldInfo>($@"
SELECT  
  TableName = case when a.colorder=1 then d.name else '' end,
  TableDesc = case when a.colorder=1 then isnull(f.value,'') else '' end,
  ID = a.colorder,
  FieldName = a.name,
  Bs = case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '1'else '0' end,
  Primarkey = case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (
  SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid))) then '1' else '0' end,
  FieldType = b.name,
  UserByte = a.length,
  Amount = COLUMNPROPERTY(a.id,a.name,'PRECISION'),
  DoubleBit = isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
  IsBeNull = case when a.isnullable=1 then '1'else '0' end,
  DefaultValue = isnull(e.text,''),
  FieldDesc = isnull(g.[value],'')
FROM  
  syscolumns a
left join  
  systypes b  
on  
  a.xusertype=b.xusertype
inner join  
  sysobjects d  
on  
  a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
left join  
  syscomments e  
on  
  a.cdefault=e.id
left join  
sys.extended_properties g  
on  
  a.id=G.major_id and a.colid=g.minor_id   
left join  


sys.extended_properties f
on  
  d.id=f.major_id and f.minor_id=0
where  
  d.name='{tableName}' --如果只查询指定表,加上此条件
order by  
  a.id,a.colorder
").ToList();
        }
    }
}
